<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

//创建一个三维场景
const scene = new THREE.Scene()
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5),
      pointLight = new THREE.PointLight(0xffffff, 0.4)
//设置点光源所在位置
pointLight.position.set(200,300,400)
//每创建一个object都需要将其添加到三维场景中
scene.add(ambientLight)
scene.add(pointLight)
//创建一个透视相机 这里的width、height是整个画布的宽高度
const width = window.innerWidth, height = window.innerHeight,
      camera = new THREE.PerspectiveCamera(45, width/height, 1, 1000)
//设置相机位置
camera.position.set(200,200,200) 
//设置相机方向
camera.lookAt(0,0,0)

//创建辅助坐标轴
// const axesHelper = new THREE.AxesHelper(100)
// scene.add(axesHelper)
//创建一个物体（形状）
const geometry = new THREE.BoxGeometry(100, 100, 100)
//创建材质（外观）
const material = new THREE.MeshLambertMaterial({
    color: 0x00fff0,//设置材质颜色
    transparent: true,//开启透明度
    opacity: 0.6 //设置透明度
})
//创建一个网格模型对象,将上面设置好的物体及其材质注入到模型对象中
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

//创建一个WebGL渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width,height)

function animate() {
    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.01;

    renderer.render(scene, camera);
};

animate();

const controls = new OrbitControls(camera, renderer.domElement)
const changeListener = controls.addEventListener('change',()=>{
    renderer.render(scene, camera)
})

const demo = ref(null)

onMounted(() => {
    document.getElementById('three')?.appendChild(renderer.domElement)
})

onUnmounted(() => {
    controls.removeEventListener(changeListener)
})
</script>

<template>
<div class="container">
    <div class="title">场景1</div>
    <div ref="demo" id="three"></div>
</div>
</template>

<style lang="scss" scoped>
.container {
    width: 100%;
    .title {
        padding: 20px;
        font-size: 20px;
    }
}
</style>